# serializers.py
from rest_framework import serializers
from users.models import Users  # 确保路径正确


class RegisterSerializer(serializers.ModelSerializer):
    # 由于密码通常需要加密存储，不会直接序列化输出，因此使用 write_only 参数
    # TODO：这里的密码加密存储还没有实现，且最小长度限制为3，需要修改
    password = serializers.CharField(write_only=True, required=True, min_length=3)
    password2 = serializers.CharField(write_only=True, required=True, min_length=3)
    username = serializers.CharField(required=True, max_length=100)

    class Meta:
        model = Users
        fields = ['username', 'password','password2']  # 包含注册时必填的字段

    def validate(self, attrs):
        # 验证两次输入的密码是否一致
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError({'password': '两次输入的密码不一致'})
        return attrs

    def create(self, validated_data):
        # 调用用户管理器的 create_user 方法创建新用户
        return Users.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
        )
